/**
 * 
 */
package com.cloud.feeling.ststem.inteceptor;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.cloud.common.CommonConstants;
import com.cloud.common.model.User;
import com.cloud.feeling.ststem.service.UserService;

/**
 *
 */
@Component
public class AuthActionInterceptor implements HandlerInterceptor {

	@Autowired
	private UserService userService;
	

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		Cookie cookie = WebUtils.getCookie(req, CommonConstants.TOKEN_COOKIE);
		String token=null;
		if(cookie != null && StringUtils.isNoneBlank(cookie.getValue())){
			token= cookie.getValue();
			User user = userService.getUserByToken(token);
			if(user != null && StringUtils.isNoneBlank(user.getId().toString())) {
				return true;
			}else {
				String msg =  URLEncoder.encode("用户失效", "utf-8");
				res.sendRedirect("http://localhost:8881/user/login?target=" + msg);
				return false;
			}
		}else {
			token= req.getHeader(CommonConstants.TOKEN_COOKIE);
			if(token != null && StringUtils.isNoneBlank(token)) {
				return true;
			}else {
				String msg =  URLEncoder.encode("请先登录", "utf-8");
				res.sendRedirect("http://localhost:8881/user/login?target=" + msg);
				return false;
			}
		}
	}

	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView)
			throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	
}
